package com.clickpaas.governmentcloud.service.policymatchextservice.impl;

import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.*;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.common.ConstantSuggest;
import com.clickpaas.governmentcloud.common.EnumCompanyType;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtService;
import com.clickpaas.governmentcloud.utils.policycondcalutils.PolicyCondCal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @company <上海爱湃斯科技有限公司>
 * @email <zhihui.peng@clickpaas.com>
 * @author huiye
 * @decription: 科技型中小企业创新资金
 * @date 2020/12/18 10:44 上午
 */
@Slf4j
@Service
public class TechSMEFundProServiceImpl implements MatchExtService {

    @Resource
    private PolicyCondCal policyCondCal;

    //企业政策常量：科技型中小企业创新资金项目
    private final static String _TECH_SME_INNOVA_FUND_PRO = ConstantExt._TECH_SME_INNOVA_FUND_PRO;

    /**
     * 跟政策是否匹配
     *
     * @param policy 匹配数据
     * @return ServerResponse
     */
    @Override
    public ServerResponse<?> isMatchSuccess(PolicyEntity policy) {
        //建议
        StringBuffer suggest = new StringBuffer();
        //返回信息
        ServerResponse<?> serverResponse = ServerResponse.createError(ConstantExt._ERROR_MESSAGE);
        //评分
        Integer score = ConstantExt._ZERO;
        //是否快速匹配：Y->true,N->false
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        //必要条件判断
        HashMap hashMap = necessCondi(policy);
        //必要条件对快速匹配数据做处理（精确匹配、快速匹配）
        boolean ifNecess=Boolean.parseBoolean(hashMap.get(ConstantExt._NECESS).toString());
        if(!ifNecess && isQuickMatch){
            return serverResponse;
        }
        //必要条件建议追加
        if (!ifNecess){
            suggest.append(ConstantSuggest._TECH_INNOV_NECESSARY);
        }
        //累加必要条件评分
        score = score + Integer.parseInt(hashMap.get(ConstantExt._SCORE).toString());
        suggest.append(hashMap.get(ConstantExt._SUGGEST).toString());


        HashMap suggAndScore = getScore(policy);
        //累加评分
        score = score + Integer.parseInt(suggAndScore.get(ConstantExt._SCORE).toString());
        //评分为0，快速匹配不展示数据
        if(score <= 0 && isQuickMatch){
            return serverResponse;
        }

        if (null == suggAndScore.get(ConstantExt._SUGGEST)
                || suggAndScore.get(ConstantExt._SUGGEST).toString().contains(suggest)){
            suggest = new StringBuffer(suggAndScore.get(ConstantExt._SUGGEST).toString());
        }else {
            suggest.append(suggAndScore.get(ConstantExt._SUGGEST).toString());
        }
        //添加建议
       /* if (suggest.length() == 0 && score >= 90) {
            suggest.append("建议申报");
        }*/
        //快速匹配不添加建议
        if (isQuickMatch){
            suggest = new StringBuffer();
        }
        //必要条件不满足得0分
        if(!ifNecess){
            score = 0;
        }
        return insertPolicyData(policy,score,suggest,serverResponse);
    }

    /**
     * 计算企业评分
     *
     * @param policy 匹配数据
     * @return HashMap
     */
    @Override
    public HashMap getScore(PolicyEntity policy) {
        HashMap<String, Object> returnValue = new HashMap<>();
        StringBuffer suggest = new StringBuffer();
        //分值
        Integer score = ConstantExt._ZERO;

        /**
         * 行业领域
         * 新一代信息技术、
         * 高端装备制造、
         * 生物与新医药、
         * 新能源与节能、
         * 新材料、
         * 新能源汽车等战略性新兴产业以及科技服务业（技术转移、科技新媒体等）领域
         */
        List<String> industrys = policy.getIndustrys();
        boolean flagNeccess = false;
        if(null != industrys
                && policyCondCal.listIntersection(industryList(),industrys)){
            score += 10;
        }else {
            flagNeccess = true;
        }
        //上年度营业收入
        if(null != policy.getBusinessIncomeOfLastYear()
                && policy.getBusinessIncomeOfLastYear()<=3000){
            score += 10;
        }else {
            flagNeccess = true;
        }
        //员工数
        if(null != policy.getEmpTotal()
                && policy.getEmpTotal()<=300){
            score += 10;
        }else {
            flagNeccess = true;
        }
        //防止添加重复的建议
        if (flagNeccess && StringUtils.isBlank(suggest)){
            suggest.append(ConstantSuggest._TECH_INNOV_NECESSARY);
        }

        /**
         * 研发人员占比
         * ≧30%	20分
         * ≧20% 10分
         * ≧10%	5分
         * <10%	0分
         */
        if(policyCondCal.RDPersonRate(policy)>=30){
            score += 20;
        }else if(policyCondCal.RDPersonRate(policy)>=20){
            score += 10;
        }else if(policyCondCal.RDPersonRate(policy)>=10){
            score += 5;
        }
        if(policyCondCal.RDPersonRate(policy)<20){
            suggest.append(ConstantSuggest._CENTER_RD_PERSONNEL);
        }
        //研发费
        if(null != policy.getDexpensesLastYear()
                && policy.getDexpensesLastYear()>40){
            score += 10;
        }else {
            suggest.append(ConstantSuggest._TECH_INNOV_RD_EXPENSES);
        }
        /**
         * 研发费用占比
         * ≧20%	20分
         * ≧10%	10分
         * ≧5%	5分
         * <5%	0分
         */
        if(policyCondCal.RDPerCostRateLastYear(policy)>=20){
            score += 20;
        }else if(policyCondCal.RDPerCostRateLastYear(policy)>=10){
            score += 10;
        }else if(policyCondCal.RDPerCostRateLastYear(policy)>=5){
            score += 5;
        }
        if(policyCondCal.RDPerCostRateLastYear(policy)<10){
            suggest.append(ConstantSuggest._TECH_INNOV_PROPORT_RD_EXPENSES);
        }
        /**
         * 知识产权
         * ≧5  	20分
         * ≧3	10分
         * ≧1	5分
         * <1	0分
         */
        Integer IntellCount = policyCondCal.IntellPropertyFirst(policy) + policyCondCal.IntellPropertySecond(policy);
        if(IntellCount>=5){
            score += 20;
        }else if(IntellCount>=3){
            score += 10;
        }else if(IntellCount>=1){
            score += 5;
        }
        if(IntellCount<3){
            suggest.append(ConstantSuggest._TECH_INNOV_INTELLECTUAL);
        }

        returnValue.put(ConstantExt._SCORE,score);
        returnValue.put(ConstantExt._SUGGEST,suggest);
        return returnValue;
    }

    /**
     * 写入匹配结果
     *
     * @param policy 匹配数据
     * @return ServerResponse
     */
    @Override
    public ServerResponse insertPolicyData(PolicyEntity policy,Integer score,StringBuffer suggest,ServerResponse serverResponse) {
        /**
         * 查询当前政策信息
         */
        TPoliciesDTO policyInfo = policyCondCal.getPolicyInfo(_TECH_SME_INNOVA_FUND_PRO);
        if (null == policyInfo) {
            log.info("政策：【{}】查询不到",_TECH_SME_INNOVA_FUND_PRO);
            return serverResponse;
        }
        policyCondCal.insertCommonPolicyData(policy, policyInfo, score, suggest);
        return ServerResponse.createSuccess(ConstantExt._SUCCESS_MESSAGE);
    }

    /**
     * 必要条件判断
     *
     * @param policy 匹配数据
     * @return HashMap
     */
    @Override
    public HashMap necessCondi(PolicyEntity policy) {
        HashMap<String, Object> map = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        map.put(ConstantExt._NECESS,true);
        StringBuffer suggStr = new StringBuffer();
        //是否快速匹配：Y->true,N->false
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        if(isQuickMatch && null == policy.getDishonesty()){
            //TODO
        }else {
            //存在知识产权纠纷、不良记录
            if(!policyCondCal.isIllegal(policy)){
                map.put(ConstantExt._NECESS,false);
            }
        }
        if(isQuickMatch && null == policy.getTobeListed()){
            //TODO
        }else {
            //非上市科技型中小企业:
            if(null != policy.getEnterpriseScale()){
                if(!(ConstantExt._ENTERPRISE_SIZE_MEDIUM.equals(policy.getEnterpriseScale())
                        || ConstantExt._ENTERPRISE_SIZE_MINIATURE.equals(policy.getEnterpriseScale())
                        || policy.getEnterpriseScale().equals(ConstantExt._ENTERPRISE_SIZE_SMALL)
                        || policy.getEnterpriseScale().equals(ConstantExt._ENTERPRISE_SIZE_MICRO))){
                    map.put(ConstantExt._NECESS,false);
                }
            }else{
                map.put(ConstantExt._NECESS,false);
            }
        }

        if(isQuickMatch && null == policy.getFinancialSupport()){
            //TODO
        }else {
            //研究内容已获财政资金支持
            if(null == policy.getFinancialSupport()
                    || ConstantExt._YES.equals(policy.getFinancialSupport())){
                map.put(ConstantExt._NECESS,false);
            }
        }
        map.put(ConstantExt._SCORE,score);
        map.put(ConstantExt._SUGGEST,suggStr);
        return map;
    }

    /**
     * 该政策支持的行业
     * @return List->默认行业数据
     */
    public List<String> industryList(){
        ArrayList<String> indusList = new ArrayList<>();
        indusList.add(EnumCompanyType._NEXTGENERINFOTECHNOLOGY.getCompanyTypeChina());
        indusList.add(EnumCompanyType._HIGHEQUIPMANUFACTURING.getCompanyTypeChina());
        indusList.add(EnumCompanyType._NEWENERGYSAVING.getCompanyTypeChina());
        indusList.add(EnumCompanyType._NEWMATERIAL.getCompanyTypeChina());
        indusList.add(EnumCompanyType._HIGHTECHSERVICE.getCompanyTypeChina());
        indusList.add(EnumCompanyType._BIOLOGYNEWMEDICINE.getCompanyTypeChina());
        indusList.add(EnumCompanyType._SOFTTECHNOSERV.getCompanyTypeChina());
        return indusList;
    }
}